package com.changgou.pay.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.pay.config.RabbitMQConfig;
import com.changgou.pay.service.WXPayService;

import com.changgou.util.ConvertUtils;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.github.wxpay.sdk.WXPayXmlUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/wxpay")
@RestController
public class WXPayController {

    @Autowired
    private WXPayService wxPayService;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    // 下单
    @GetMapping("/nativePay")
    public Result nativePay(@RequestParam("orderId") String orderid, @RequestParam("money") Integer money) {

        Map map = wxPayService.nativePay(orderid, money);
        System.out.println(map);
        if (map == null) {
            return new Result(false, StatusCode.ERROR, "map为null", map);
        } else {
            return new Result(true, StatusCode.OK, "map不为null", map);
        }


    }


    @RequestMapping("/notify")
    public void notifyLogic(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("支付成功回调");

        try {
            // 获取输入流，并转换成xml
            String xml = ConvertUtils.convertToString(request.getInputStream());
            System.out.println(xml);
            // 将xml转换为map
            Map<String, String> toMap = WXPayUtil.xmlToMap(xml);
            String result_code = toMap.get("result_code");  // 获取成功码
            // 判断微信返回的信息是否是成功
            if ("SUCCESS".equals(result_code)) {
                // 成功，返回订单号
                Map result = wxPayService.queryOrder(toMap.get("out_trade_no"));
                System.out.println("查询订单结果" + result);
                // 通过rabbitMQ发送消息到order服务
                Map message = new HashMap();
                message.put("orderId", result.get("out_trade_no"));
                message.put("transactionId", result.get("transaction_id"));
                // 当前不需要用交换机，给一个 "" ;
                rabbitTemplate.convertAndSend("", RabbitMQConfig.ORDER_PAY, JSON.toJSONString(message));
                //完成双向通信
                rabbitTemplate.convertAndSend("paynotify", "", result.get("out_trade_no"));

            } else {
                // 输出错误原因
                System.out.println(toMap.get("err_code_des"));

            }

            // 给微信响应消息
            response.setContentType("text/xml");
            String data = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            response.getWriter().write(data);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }


    // 查询微信订单
    @GetMapping("/queryorder/{orderId}")
    public Result queryOrder(@PathVariable("orderId") String orderId) {

        Map map = wxPayService.queryOrder(orderId);
        return new Result(true, StatusCode.OK, "查询微信订单成功", map);
    }


    // 基于微信关闭订单
    @PutMapping("/close/{orderId}")
    public Result closeOrder(@PathVariable("orderId") String orderId) {

        Map map = wxPayService.closeOrder(orderId);
        return new Result(true, StatusCode.OK, "关闭微信订单成功", map);

    }
}
